<template>
  <div>
    <div class="my-[8px]"><VActionBar :actions="actions" /></div>
    <vxe-grid ref="tableRef" v-bind="tableOptions" />
    <RuleDialog
      :value="selectItem"
      v-model="visible"
      :optionsData="optionsData"
      @close="selectItem = {}"
      @refresh="handleRefresh"
    />
  </div>
</template>
<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import ActionBar from '@/components/ActionBar/index.vue'

import RuleDialog from '../RuleDialog/index.vue'

import { auditList, statusAudit, deleteAudit } from '../../../api'

const { proxy } = getCurrentInstance()

const props = defineProps({
  params: { type: Object, default: () => ({}) },
  id: { type: String, default: '' },
  optionsData: { type: Object, default: () => ({}) },
})
const visible = ref()
const tableRef = ref()
const selectItem = ref()

const tableOptions = {
  pagerConfig: { pageSize: 20 },
  round: true,
  height: '400px',
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  columns: [
    { fixed: 'left', width: 50, type: 'checkbox' },
    {
      fixed: 'left',
      title: '策略名称',
      minWidth: 120,
      field: 'rule_name',
    },
    {
      title: '费用类型',
      width: 200,
      field: 'fee_type_text',
    },
    { title: '物流商', width: 200, field: 'logistics_ids_text' },
    {
      title: '账单总费用减去系统总费用\n范围(RMB)',
      width: 200,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.total_bill_variance_min} - {row.total_bill_variance_max}
            </div>
          )
        },
      },
    },
    {
      title: '账单费用减去系统费用\n范围(RMB)(单数据)',
      width: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.system_cost_variance_min} - {row.system_cost_variance_max}
            </div>
          )
        },
      },
    },
    {
      title: '账单重量减去系统重量\n范围(g)(单数据)',
      width: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.weight_variance_min} - {row.weight_variance_max}
            </div>
          )
        },
      },
    },
    {
      title: '执行条件：\n对账批次符合条件则',
      width: 180,
      field: 'submit_type_text',
    },
    { title: '状态', width: 100, field: 'status_text' },
    {
      title: '操作',
      minWidth: 80,
      fixed: 'right',
      align: 'center',
      slots: {
        default: ({ row, rowIndex }) => {
          return (
            <div>
              <el-button link type='primary' onClick={() => handleEdit(row)}>
                编辑
              </el-button>
            </div>
          )
        },
      },
    },
  ],
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: 'data',
      total: 'total',
    },
    ajax: {
      query: ({ page }) => {
        const { params } = props
        return auditList({
          ...page,
          ...params,
        })
      },
    },
  },
}

const getTableData = () => {
  return tableRef.value.getTableData().tableData
}

const commitProxy = () => {
  return tableRef.value.commitProxy
}

const handleEdit = item => {
  selectItem.value = JSON.parse(
    JSON.stringify({
      ...item,
    })
  )
  visible.value = true
}

const getSelectRows = () => {
  const rows = tableRef.value?.getCheckboxRecords()
  if (!rows?.length) {
    ElMessage({
      showClose: true,
      message: '请至少选择一条数据！',
      type: 'warning',
    })
    return []
  }
  return rows
}

const handleStatus = status => {
  const rows = getSelectRows()
  if (!rows.length) return
  const id = rows.map(n => n.id)
  handleStatusReq(id, status)
}

const handleStatusReq = (id, flag) => {
  proxy?.confirm({
    title: '提示',
    content: (
      <p>
        确认{flag ? '启用' : '禁用'}选中的
        <span class='text-[#3366F1] px-[4px]'>{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        try {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '处理中..'
          await statusAudit({ id, status: flag ? 1 : 0 })
          ElMessage.success('操作成功')
        } catch (e) {
          console.error(e)
        } finally {
          instance.confirmButtonLoading = false
          done()
          handleRefresh()
        }
      } else {
        done()
      }
    },
  })
}

const handleDelete = () => {
  const rows = getSelectRows()
  if (!rows.length) return
  const id = rows.map(n => n.id)
  proxy?.confirm({
    title: '提示',
    content: (
      <p>
        确认删除选中的
        <span class='text-[#3366F1] px-[4px]'>{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        try {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '处理中..'
          await deleteAudit({ id })
          ElMessage.success('操作成功')
        } catch (e) {
          console.error(e)
        } finally {
          instance.confirmButtonLoading = false
          done()
          handleRefresh()
        }
      } else {
        done()
      }
    },
  })
}

const handleRefresh = () => {
  tableRef.value.commitProxy('reload')
}

defineExpose({ getTableData, handleRefresh })

const actions = [
  {
    label: '新增',
    icon: 'add',
    type: 'primary',
    fn: () => (visible.value = true),
  },
  { label: '删除', icon: 'del', fn: handleDelete },
  {
    label: '启用',
    icon: 'state_finish_line',
    fn: () => handleStatus(true),
  },
  {
    label: '禁用',
    icon: 'state_disabled',
    fn: () => handleStatus(false),
  },
]
</script>
